package com.supcalls.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.supcalls.entity.User;
import com.supcalls.service.IUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Resource
    private IUserService userService;

    /** 查询所有用户 */
    @GetMapping
    public List<User> getAllUsers() {
        return userService.list();
    }

    /** 根据 ID 查询用户 */
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getById(id);
    }

    /** 添加用户 */
    @PostMapping
    public boolean createUser(@RequestBody User user) {
        return userService.save(user);
    }

    /** 更新用户 */
    @PutMapping
    public boolean updateUser(@RequestBody User user) {
        return userService.updateById(user);
    }

    /** 根据 ID 删除用户 */
    @DeleteMapping("/{id}")
    public boolean deleteUser(@PathVariable Long id) {
        return userService.removeById(id);
    }

    /** 查询年龄大于某个值的用户 */
    @GetMapping("/ageGreaterThan/{age}")
    public List<User> getUsersOlderThan(@PathVariable Integer age) {
        return userService.list(new QueryWrapper<User>().gt("age", age));
    }

    /** 根据名字模糊查询用户 */
    @GetMapping("/search")
    public List<User> searchUsersByName(@RequestParam String name) {
        return userService.list(new QueryWrapper<User>().like("name", name));
    }

    /** 查询所有用户并分页 */
    @GetMapping("/page")
    public IPage<User> getUsersByPage(@RequestParam(defaultValue = "1") int pageNum,
                                      @RequestParam(defaultValue = "10") int pageSize) {
        Page<User> page = new Page<>(pageNum, pageSize);
        return userService.page(page);
    }

    /** 查询年龄在某个范围内的用户（10 <= age <= 30） */
    @GetMapping("/ageBetween")
    public List<User> getUsersByAgeRange(@RequestParam Integer minAge, @RequestParam Integer maxAge) {
        return userService.list(new QueryWrapper<User>().between("age", minAge, maxAge));
    }

    /** 查询邮箱后缀为 @example.com 的用户 */
    @GetMapping("/emailDomain")
    public List<User> getUsersByEmailDomain(@RequestParam String domain) {
        return userService.list(new QueryWrapper<User>().likeRight("email", domain));
    }

    /** 查询最新添加的 N 个用户 */
    @GetMapping("/latest")
    public List<User> getLatestUsers(@RequestParam(defaultValue = "5") int limit) {
        return userService.list(new QueryWrapper<User>().orderByDesc("id").last("LIMIT " + limit));
    }
}
